/*
 * File: TUSocket.cpp
 * Author: Michael Sautter

 * Created on April 8th, 2011, 5:03p.m.
 */

#include "TigerUpdate.h"
#include <cstdlib>
#include <iostream>
#include <sys/types.h>
#include <string.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

/* Default Constructor */
TUSocket::TUSocket(){
    myTUAddress = NULL;
    mySock = 0;
}

/* Constructor with passed TUAddress as a parameter */
TUSocket::TUSocket(TUAddress *address){
    setAddress(address);
    mySock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
}

TUSocket::~TUSocket(){

}

int TUSocket::setAddress(TUAddress *address){
    myTUAddress = *address;
    if(myTUAddress == address){
        return 0;
    }
    else{
        return -1;
    }
}

TUAddress *TUSocket::getAddress(){
    return &myTUAddress;
}

int TUSocket::bindMe(){
    if(bind(
            mySock,
            (sockaddr *)(myTUAddress.getSockAddr()),
            sizeof(myTUAddress.getSockAddr())
           ) < 0){
        return -1;
    }
    else{
        return 0;
    }
}

int TUSocket::recvMe(TUObject *recv, TUAddress *returnAddress){
    socklen_t size = sizeof(struct sockaddr_storage);
    int code = recvfrom(
        mySock,
        recv,
        sizeof(recv),
        0,
        (sockaddr *)returnAddress->getSockAddr(),
        &size);
    if(code < 0){
        return -1; //error on recieve
    }
    else{
        return code;
    }

}

int TUSocket::sendMe(TUObject *data){
    unsigned int sentSize;
    if(
        (connect(mySock, (struct sockaddr *) &myTUAddress, sizeof(myTUAddress)))
            < 0){
        return -1;
    }
    sentSize = send(mySock, data, sizeof(&data), 0);
    return sentSize;
}

